from fastapi import FastAPI
from fastapi.exceptions import RequestValidationError
from fastapi_authz import CasbinMiddleware
from starlette.exceptions import HTTPException
from starlette.middleware.authentication import AuthenticationMiddleware
from starlette.middleware.cors import CORSMiddleware
from starlette.responses import PlainTextResponse

import auth.permission.route
import auth.role.route
import auth.user.route
from auth.jwt.service import JWTAuthenticationBackend
from auth.role.service import enforcer
from conf.config import init_database

app = FastAPI()
app.add_middleware(CasbinMiddleware, enforcer=enforcer)
app.add_middleware(AuthenticationMiddleware, backend=JWTAuthenticationBackend())
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.on_event("startup")
async def start_database():
    await init_database()


@app.exception_handler(HTTPException)
async def http_exception_handler(request, exc):
    return PlainTextResponse(str(exc.detail), status_code=exc.status_code)


@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
    return PlainTextResponse(str(exc), status_code=400)


@app.get("/", tags=["Root"])
async def read_root():
    return {"message": "Welcome to this fantastic app."}


app.include_router(auth.permission.route.router, tags=["Permission"], prefix="/auth/permission")
app.include_router(auth.role.route.router, tags=["Role"], prefix="/auth/role")
app.include_router(auth.user.route.router, tags=["User"], prefix="/auth/user")
